// 商品维护页面
Page({
  data: {
    productList: [],
    loading: false,
    showAddModal: false,
    editingProduct: null,
    productImageList: [], // 商品图片列表
    formData: {
      title: "",
      description: "",
      price: "",
      image: "",
    },
  },

  onLoad() {
    // 延迟加载，确保页面完全初始化
    setTimeout(() => {
      this.loadProductList();
    }, 100);
  },

  onShow() {
    // 只在页面显示时重新加载，避免重复调用
    if (this.data.productList.length === 0) {
      this.loadProductList();
    }
  },

  /**
   * 加载商品列表
   */
  async loadProductList() {
    this.setData({ loading: true });

    try {
      // 优先从API加载商品数据
      const { productApi } = require("../../utils/api.js");
      const result = await productApi.getProducts();

      if (result.code === 0) {
        // API数据加载成功
        const products = result.data.list.map((item) => {
          // 处理图片路径
          let imageUrl = "";
          if (item.images && item.images.trim()) {
            // 只有当URL是相对路径时才添加域名前缀
            if (
              item.images.startsWith("/uploads/") &&
              !item.images.startsWith("http")
            ) {
              // 如果是相对路径，转换为完整URL
              const { imageServerURL } = require("../../config.js");
              imageUrl = `${imageServerURL}${item.images}`;
            } else if (item.images.startsWith("http")) {
              // 如果已经是完整URL，直接使用
              imageUrl = item.images;
            } else {
              // 其他情况保持原样
              imageUrl = item.images;
            }
          }

          return {
            id: item.id,
            title: item.name,
            description: item.description,
            price: item.price.toString(),
            image: imageUrl,
            stock: item.stock,
            sort: item.sort,
            status: item.status,
          };
        });

        this.setData({
          productList: products,
          loading: false,
        });

        // 商品数据已从数据库加载完成

        // 显示成功提示
        if (products.length > 0) {
          wx.showToast({
            title: `加载了${products.length}个商品`,
            icon: "success",
            duration: 1000,
          });
        }
      } else {
        throw new Error(result.message || "API加载失败");
      }
    } catch (error) {
      // API失败时显示错误信息
      this.setData({
        productList: [],
        loading: false,
      });

      wx.showToast({
        title: "加载失败，请检查网络",
        icon: "none",
        duration: 2000,
      });
    }
  },

  /**
   * 添加商品
   */
  addProduct() {
    this.setData({
      showAddModal: true,
      editingProduct: null,
      productImageList: [],
      formData: {
        title: "",
        description: "",
        price: "",
        image: "",
      },
    });
  },

  /**
   * 编辑商品
   */
  editProduct(e) {
    const { product } = e.currentTarget.dataset;

    // 设置商品图片列表
    let productImageList = [];
    if (product.image && product.image.trim()) {
      // 处理图片路径，确保是完整的URL
      let imageUrl = product.image;
      // 只有当URL是相对路径时才添加域名前缀
      if (
        product.image.startsWith("/uploads/") &&
        !product.image.startsWith("http")
      ) {
        // 如果是相对路径，转换为完整URL
        const { imageServerURL } = require("../../config.js");
        imageUrl = `${imageServerURL}${product.image}`;
      }

      productImageList = [
        {
          url: imageUrl,
          status: "done",
          message: "已上传",
        },
      ];
    }

    this.setData({
      showAddModal: true,
      editingProduct: product,
      productImageList: productImageList,
      formData: {
        title: product.title,
        description: product.description,
        price: product.price,
        image: product.image,
      },
    });
  },

  /**
   * 删除商品
   */
  deleteProduct(e) {
    const { product } = e.currentTarget.dataset;

    wx.showModal({
      title: "确认删除",
      content: `确定要删除商品"${product.title}"吗？`,
      success: (res) => {
        if (res.confirm) {
          this.confirmDelete(product.id);
        }
      },
    });
  },

  /**
   * 确认删除商品
   */
  async confirmDelete(productId) {
    // 检查用户是否已登录
    const token = wx.getStorageSync("token");
    if (!token) {
      wx.showToast({
        title: "请先登录",
        icon: "none",
      });
      return;
    }

    try {
      const { productApi } = require("../../utils/api.js");
      const result = await productApi.deleteProduct(productId);

      if (result.code === 0) {
        wx.showToast({
          title: "删除成功",
          icon: "success",
        });

        // 重新加载商品列表
        this.loadProductList();
      } else {
        throw new Error(result.message || "删除失败");
      }
    } catch (error) {
      wx.showToast({
        title: error.message || "删除失败",
        icon: "none",
      });
    }
  },

  /**
   * 商品图片上传后处理
   */
  async afterReadProductImage(event) {
    const { file } = event.detail;

    // 显示上传中状态
    const { productImageList = [] } = this.data;
    const newFile = {
      ...file,
      status: "uploading",
      message: "上传中...",
    };
    productImageList.push(newFile);
    this.setData({ productImageList });

    try {
      // 实际上传图片到服务器
      const { productApi } = require("../../utils/api.js");

      // 使用正确的文件路径
      let filePath = file.tempFilePath || file.path || file.url;

      // 检查文件大小并压缩
      const fileInfo = await new Promise((resolve) => {
        wx.getFileInfo({
          filePath: filePath,
          success: resolve,
          fail: () => resolve({ size: 0 }),
        });
      });

      const fileSizeKB = fileInfo.size / 1024;

      // 如果文件超过1.5MB，进行压缩
      if (fileSizeKB > 1500) {
        filePath = await new Promise((resolve) => {
          wx.compressImage({
            src: filePath,
            quality: 0.3, // 降低压缩质量
            success: (res) => {
              // 检查压缩后的文件大小
              wx.getFileInfo({
                filePath: res.tempFilePath,
                success: (compressedInfo) => {
                  const compressedSizeKB = compressedInfo.size / 1024;
                  resolve(res.tempFilePath);
                },
                fail: () => resolve(res.tempFilePath),
              });
            },
            fail: () => resolve(filePath),
          });
        });
      }

      // 最终检查文件大小，确保不超过2MB
      const finalFileInfo = await new Promise((resolve) => {
        wx.getFileInfo({
          filePath: filePath,
          success: resolve,
          fail: () => resolve({ size: 0 }),
        });
      });

      const finalSizeKB = finalFileInfo.size / 1024;

      if (finalSizeKB > 2000) {
        throw new Error(
          `商品图片过大 (${finalSizeKB.toFixed(2)}KB)，请选择更小的图片`
        );
      }

      const result = await productApi.uploadImage(filePath);

      if (result.code === 0) {
        // 上传成功，更新文件状态和formData
        const updatedImageList = productImageList.map((item, index) => {
          if (index === productImageList.length - 1) {
            return {
              ...item,
              url: result.data.url, // 使用服务器返回的URL
              status: "done",
              message: "上传成功",
            };
          }
          return item;
        });

        this.setData({
          productImageList: updatedImageList,
          "formData.image": result.data.url,
        });

        wx.showToast({
          title: "图片上传成功",
          icon: "success",
        });
      } else {
        throw new Error(result.message || "上传失败");
      }
    } catch (error) {
      // 上传失败，更新文件状态
      const updatedImageList = productImageList.map((item, index) => {
        if (index === productImageList.length - 1) {
          return {
            ...item,
            status: "failed",
            message: "上传失败",
          };
        }
        return item;
      });

      this.setData({ productImageList: updatedImageList });

      wx.showToast({
        title: error.message || "上传失败",
        icon: "none",
        duration: 2000,
      });
    }
  },

  /**
   * 删除商品图片
   */
  deleteProductImage(event) {
    const { index } = event.detail;
    const { productImageList = [] } = this.data;

    productImageList.splice(index, 1);
    this.setData({
      productImageList,
      "formData.image":
        productImageList.length > 0 ? productImageList[0].url : "",
    });
  },

  /**
   * 预览商品图片
   */
  previewProductImage(event) {
    const { index } = event.detail;
    const { productImageList = [] } = this.data;

    if (productImageList[index] && productImageList[index].url) {
      wx.previewImage({
        urls: [productImageList[index].url],
      });
    }
  },

  /**
   * 预览图片
   */
  previewImage() {
    if (this.data.formData.image) {
      wx.previewImage({
        urls: [this.data.formData.image],
      });
    }
  },

  /**
   * 输入框变化
   */
  onInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;

    this.setData({
      [`formData.${field}`]: value,
    });
  },

  /**
   * 保存商品
   */
  async saveProduct() {
    const { formData, editingProduct } = this.data;

    // 验证表单
    if (!formData.title || !formData.title.trim()) {
      wx.showToast({
        title: "请输入商品标题",
        icon: "none",
      });
      return;
    }

    if (!formData.description || !formData.description.trim()) {
      wx.showToast({
        title: "请输入商品描述",
        icon: "none",
      });
      return;
    }

    if (!formData.price || !formData.price.trim()) {
      wx.showToast({
        title: "请输入商品价格",
        icon: "none",
      });
      return;
    }

    // 检查用户是否已登录
    const token = wx.getStorageSync("token");
    if (!token) {
      wx.showToast({
        title: "请先登录",
        icon: "none",
      });
      return;
    }

    try {
      const { productApi } = require("../../utils/api.js");

      const productData = {
        name: formData.title,
        description: formData.description,
        price: parseFloat(formData.price),
        stock: 100, // 默认库存
        images: formData.image || "",
        sort: 1,
      };

      let result;
      if (editingProduct) {
        // 编辑商品
        result = await productApi.updateProduct(editingProduct.id, productData);
      } else {
        // 添加新商品
        result = await productApi.createProduct(productData);
      }

      if (result.code === 0) {
        wx.showToast({
          title: editingProduct ? "商品更新成功" : "商品添加成功",
          icon: "success",
        });

        // 关闭弹窗
        this.setData({
          showAddModal: false,
          editingProduct: null,
          formData: {
            title: "",
            description: "",
            price: "",
            image: "",
          },
        });

        // 重新加载商品列表
        this.loadProductList();
      } else {
        throw new Error(result.message || "保存失败");
      }
    } catch (error) {
      wx.showToast({
        title: error.message || "保存失败",
        icon: "none",
      });
    }
  },

  /**
   * 取消保存
   */
  cancelSave() {
    this.setData({
      showAddModal: false,
      editingProduct: null,
      productImageList: [],
      formData: {
        title: "",
        description: "",
        price: "",
        image: "",
      },
    });
  },

  /**
   * 输入框变化处理
   */
  onInputChange(e) {
    const { field } = e.currentTarget.dataset;
    let value;

    // 处理不同的事件结构
    if (e.detail && typeof e.detail === "object") {
      value = e.detail.value || e.detail;
    } else {
      value = e.detail;
    }

    this.setData({
      [`formData.${field}`]: value,
    });
  },

  /**
   * 清空所有商品
   */
  clearAllProducts() {
    wx.showModal({
      title: "确认清空",
      content: "确定要清空所有商品吗？此操作不可恢复！",
      success: (res) => {
        if (res.confirm) {
          try {
            wx.removeStorageSync("products");
            this.loadProductList();
            wx.showToast({
              title: "已清空所有商品",
              icon: "success",
            });
          } catch (error) {
            wx.showToast({
              title: "清空失败",
              icon: "none",
            });
          }
        }
      },
    });
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    // 重新加载商品数据
    this.loadProducts();

    // 停止下拉刷新动画
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  /**
   * 上拉加载更多
   */
  onReachBottom() {
    // 商品维护页面通常不需要分页加载，因为商品数量不会太多
    wx.showToast({
      title: "没有更多商品了",
      icon: "none",
      duration: 1500,
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: "甲年华美甲美睫 - 产品展示",
      desc: "查看我们的美甲产品和服务，选择最适合您的款式",
      path: "/pages/productMaintain/index",
      imageUrl: "/images/share-products.jpg",
    };
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: "甲年华美甲美睫 - 产品展示",
      query: "",
      imageUrl: "/images/share-products.jpg",
    };
  },
});
